import instance from "./requests";
// key:da31338ed254c1cdbc3c43a6e6742f0e
// 通过ip查询所在城市
// 请求示例：https://restapi.amap.com/v3/ip?ip=114.247.50.2&key=<用户的 key>
export const getCityByIp = async () => {
    const res = await instance.get("/ip");
    return res.city;
};

// 通过城市名查询adcode
// 请求示例：https://restapi.amap.com/v3/geocode/geo?address=北京市&key=<用户的 key>
export const getAdcodeByCity = async (city) => {
    const res = await instance.get("/geocode/geo", {
        params: {
            address: city,
        },
    });
    return res.geocodes[0].adcode;
};
// 通过adcode查询城市天气
// 请求示例：https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=<用户 key>&extensions=all
export const getWeatherByAdcode = async (adcode) => {
    const res = await instance.get("/weather/weatherInfo", {
        params: {
            city: adcode,
            extensions: "all",
        },
    });
    // 解析未来4天
    const forecastData = res.forecasts[0].casts;

    return forecastData;
};
// 通过adcode查询当天城市天气
export const getTodayWeatherByAdcode = async (adcode) => {
    const res = await instance.get("/weather/weatherInfo", {
        params: {
            city: adcode,
            extensions: "base",
        },
    });
    return res.lives[0];
};
// 搜索城市
// 请求示例：https://restapi.amap.com/v3/geocode/geo?address=北京&key=<用户的key>
export const searchCity = async (keyword) => {
    if (!keyword) return null;

    const res = await instance.get("/geocode/geo", {
        params: {
            address: keyword,
        },
    });

    if (res.geocodes && res.geocodes.length > 0) {
        return res.geocodes.map((item) => ({
            name: item.city || item.province, // 如果没有city就使用province
            adcode: item.adcode,
            address: item.formatted_address,
        }));
    }
    return [];
};
